Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

77
Views
Agrupe y cree tres nuevas columnas por condición [Bajo, Alcanzado, Alto]

Tengo un gran conjunto de datos (~5 millones de filas) con resultados de un entrenamiento de Machine Learning. Ahora quiero verificar si los resultados alcanzan el "rango objetivo" o no. Digamos que este rango contiene todos los valores entre -0.25 y +0.25 . Si está dentro de este rango, es un Hit , si está por debajo de Low y en el otro lado High .

Ahora crearía estas tres columnas Hit, Low, High y calcularía para cada fila qué condición se aplica y pondría un 1 en esta columna, los otros dos se convertirían en 0 . Después de eso, agruparía los valores y los resumiría. Pero sospecho que debe haber una forma mejor y más rápida, como calcularlo directamente mientras se agrupa. Estoy feliz por cualquier idea.


Datos

 import pandas as pd df = pd.DataFrame({"Type":["RF", "RF", "RF", "MLP", "MLP", "MLP"], "Value":[-1.5,-0.1,1.7,0.2,-0.7,-0.6]}) +----+--------+---------+ | | Type | Value | |----+--------+---------| | 0 | RF | -1.5 | <- Low | 1 | RF | -0.1 | <- Hit | 2 | RF | 1.7 | <- High | 3 | MLP | 0.2 | <- Hit | 4 | MLP | -0.7 | <- Low | 5 | MLP | -0.6 | <- Low +----+--------+---------+

Rendimiento esperado

 pd.DataFrame({"Type":["RF", "MLP"], "Low":[1,2], "Hit":[1,1], "High":[1,0]}) +----+--------+-------+-------+--------+ | | Type | Low | Hit | High | |----+--------+-------+-------+--------| | 0 | RF | 1 | 1 | 1 | | 1 | MLP | 2 | 1 | 0 | +----+--------+-------+-------+--------+
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Puede usar cut para definir los grupos y pivot_table para remodelar:

 (df.assign(group=pd.cut(df['Value'], [float('-inf'), -0.25, 0.25, float('inf')], labels=['Low', 'Hit', 'High'])) .pivot_table(index='Type', columns='group', values='Value', aggfunc='count') .reset_index() .rename_axis(None, axis=1) )

O crosstab :

 (pd.crosstab(df['Type'], pd.cut(df['Value'], [float('-inf'), -0.25, 0.25, float('inf')], labels=['Low', 'Hit', 'High']) ) .reset_index().rename_axis(None, axis=1) )

producción:

 Type Low Hit High 0 MLP 2 1 0 1 RF 1 1 1
over 4 years ago · Santiago Trujillo Report

0

Puede assign con np.select luego crosstab

 c1 = df.Value<=-0.25 c2 = df.Value>=0.25 out = pd.crosstab(df['Type'], np.select([c1,c2], ['Low','High'], default='Hit')) out Out[32]: col_0 High Hit Low Type MLP 0 1 2 RF 1 1 1
over 4 years ago · Santiago Trujillo Report

0

puedes probar esto:

 # Your code import pandas as pd df = pd.DataFrame({"Type":["RF", "RF", "RF", "MLP", "MLP", "MLP"], "Value":[-1.5,-0.1,1.7,0.2,-0.7,-0.6]}) # Set your range RANGE_MIN = -0.25 RANGE_MAX = 0.25 # --- define functions to be applied to df --- # evaluate if value is a low def eval_low(value): if value < RANGE_MIN: return 1 else: return 0 # evaluate if value is a high def eval_high(value): if value > RANGE_MAX: return 1 else: return 0 # evaluate if value is a hit def eval_hit(value): if value >= RANGE_MIN and value <= RANGE_MAX: return 1 else: return 0 # Evaluate the functions in new columns df['Low'] = df.Value.apply(eval_low) df['Hit'] = df.Value.apply(eval_hit) df['High'] = df.Value.apply(eval_high) # get the summary df.groupby('Type').sum()
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!